<?php
namespace app\admin\controller;

use app\admin\model\CarModel;
use my\Security;
use think\Db;
use my\Tools;
use app\admin\model\RegionModel;
use think\Env;
use app\admin\model\AdminModel;

class Carcj extends Base
{
    public $ext = array('jpg', 'gif', 'png', 'jpeg');//允许上传图片的类型
    protected  $map = array('auth_status'=>1,'record_status'=>1);//只显示通过审核的司机
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $areaInfo = AdminModel::getRoleArea();
        if(!empty($areaInfo)){
            $this->map['a.work_city'] = ['in',implode(',',$areaInfo['city'])];
        }
    }

    //车辆列表
    public function index()
    {
        $page       = input('get.page');
        $limit      = input('get.limit');
        $driver_type= input('get.driver_type');
        if($page && $limit){
            $data = input('get.');
            if(!empty($data['start'])){         //车辆注册开始时间
                $this->map['register_at'] = ['>=',strtotime($data['start'])];
            }
            if(!empty($data['end'])){           //车辆注册结束时间
                $this->map['register_at'] = ['<=',strtotime($data['end']." 23:59:59")];
            }
            if(!empty($data['start']) && !empty($data['end'])){         //车辆注册开始时间
                $this->map['register_at'] = ['between',[strtotime($data['start']),strtotime($data['end']." 23:59:59")]];
            }
            if(!empty($data['driver_phone'])){  //手机号
                $this->map['driver_phone'] = Security::encrypt($data['driver_phone']);
            }
            if(!empty($data['car_plate'])){     //车牌号
                $this->map['car_plate'] = Security::encrypt($data['car_plate']);
            }
            if(!empty($driver_type)){
                $this->map['driver_type'] = $driver_type;
            }
            $model_car = new CarModel();
            $res    = $model_car->getCarList($page, $limit, $this->map,'car_id,driver_name,driver_phone,car_plate,car_brand,car_model,color,owner,register_at,auth_status,franchisee_type,franchisee_id');
            $count  = Db::name('car_info a')->join('driver_base b','a.driver_id = b.driver_id','LEFT')->join('driver_info c','b.driver_id = c.driver_id','LEFT')->where($this->map)->count();
            //$res = decode_array_2($res);
            //判断是否已补录
            foreach($res as $key => $value) {
                $res[$key]['driver_phone']  = Security::decrypt($value['driver_phone']);
                $res[$key]['car_plate']     = Security::decrypt($value['car_plate']);
                $res[$key]['car_brand']     = Security::decrypt($value['car_brand']);
                $res[$key]['car_model']     = Security::decrypt($value['car_model']);
                $res[$key]['color']         = Security::decrypt($value['color']);
                $res[$key]['owner']         = Security::decrypt($value['owner']);
                $res[$key]['register_at']   = !empty($value['register_at'])?date("Y-m-d",$value['register_at']):'';

                $franchisee_info = '';
                if($value['franchisee_type'] == 4) { //快车租赁公司
                    $res[$key]['franchisee_type'] = '快车租赁公司';
                    $franchisee_info = Db::connect('db2')->table('franchisee')->field('name')->where(['id'=>$value['franchisee_id'],'is_delete'=>0])->find();
                } elseif($value['franchisee_type'] == 5) {
                    $res[$key]['franchisee_type'] = '城际车队公司';
                    $franchisee_info = Db::connect('db2')->table('fleet')->field('name')->where(['id'=>$value['franchisee_id'],'is_delete'=>0])->find();
                } else {
                    $res[$key]['franchisee_type'] = '-';
                }
                if($franchisee_info) {
                    $res[$key]['franchisee_name'] = $franchisee_info['name'];
                } else {
                    $res[$key]['franchisee_name'] = '-';
                }
                $data = Db::name('car_info_supplement')->where('car_id', $value['car_id'])->find();
                if($data) {
                    $res[$key]['is_supplement'] = 1; //已补录
                } else {
                    $res[$key]['is_supplement'] = 2; //未补录
                }
            }
            echo json_encode(array(
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $res
            ));die;
        }
        $this->assign('driver_type', $driver_type);
        return $this->fetch();
    }

    //详情
    public function detail()
    {
        $car_id = input('get.car_id');
        $car = new CarModel();
        $car_detail_column = get_car_detail_column();
        unset($car_detail_column['work_province']);
        $column = array_merge($car_detail_column,get_car_img_column()) ;
        $control = input('get.control');
        $thumb = config('car_img_thumb_field').config('driver_img_thumb_field');
        if($control!='auth'){
            unset($column['id_front']);
            unset($column['id_back']);
            unset($column['id_hold']);
            $thumb = config('car_img_thumb_field');
        }
        $info = $car->getCarById($car_id,implode(',',array_keys($column)).$thumb.',auth_type as att');
        if($info){
            $info = decode_array($info);
            $info['car_vin'] = Security::decrypt($info['car_vin']);
            //网约车不要上传 -----------车辆运输证和服务资格证
            if($info['att']==1){unset($column['taxi']);unset($column['taxi_certificate']);}
            $config['fields'] = $column;
            $config['info'] = $info;
            $config['img'] = array_keys(get_car_img_column());
            $config['auth_status'] = auth_status();
            $config['auth_type'] = auth_type();
            $this->assign($config);
            return view();
        }
    }
    /**
     * 车辆信息修改
     * @param string
     * @param int  car_id
     * @return edit.html
     */
    public function edit()
    {
        $car_id = input('get.car_id');
        $car = new CarModel();
        $car_detail_column = get_car_detail_column();
        unset($car_detail_column['work_province']);

        $column = array_merge($car_detail_column,get_car_img_column()) ;
        $control = input('get.control');
        $thumb = config('car_img_thumb_field').config('driver_img_thumb_field');
        if($control!='auth'){
            unset($column['id_front']);
            unset($column['id_back']);
            unset($column['id_hold']);
            $thumb = config('car_img_thumb_field');
        }
        $info = $car->getCarById($car_id,'car_id,'.implode(',',array_keys($column)).$thumb.',auth_type as att');

        if($info){
            $info = decode_array($info);
            $info['auth_type'] = auth_type()[$info['auth_type']];
            //网约车不要上传 -----------车辆运输证和服务资格证
//            if($info['att']==1){unset($column['taxi']);unset($column['taxi_certificate']);}
            $config['fields'] = $column;
            $config['info'] = $info;
            $config['img'] = array_keys(get_car_img_column());
            $config['auth_status'] = auth_status();
            $config['auth_type'] = auth_type();
            $this->assign($config);
            return view();
        }
    }

    //车辆信息补录
    public function supplement()
    {
            $car_id = input('get.car_id');
            //补录信息表
            $info = Db::table('xm_car_info_supplement')->where('car_id',$car_id)->find();
            if($info) {
                foreach ($info as $key => $value) {
                    if($key != 'car_id' && $key != 'city_code' && $key != 'plate_color' && $key != 'inspection_status' && $key != 'annual_review_status' && $key != 'service_type') {
                        $info[$key] = Security::decrypt($value);
                    }
                }
                $region_data = Db::table('xm_region c')
                    ->join(['xm_region'=>'p'], 'p.region_id = c.parent_id', 'LEFT')
                    ->field('c.region_id as city_id, c.region_name as city_name, p.region_id as province_id, p.region_name as province_name')
                    ->where('c.region_code', $info['city_code'])
                    ->find();

                $this->assign('region_data',$region_data);

                $plate_color_select = [$info['plate_color'] => plate_color()[$info['plate_color']]]; //车牌颜色
                $energy_type_select = [$info['energy_type'] => fuel_type()[$info['energy_type']]];
                $inspection_status_select = [$info['inspection_status'] => fix_state()[$info['inspection_status']]]; //车辆检修状态
                $annual_review_status = [$info['annual_review_status'] => check_state()[$info['annual_review_status']]]; //车辆年度审验状态

                $this->assign('plate_color_select',$plate_color_select);
                $this->assign('energy_type_select',$energy_type_select);
                $this->assign('inspection_status_select',$inspection_status_select);
                $this->assign('annual_review_status_select',$annual_review_status);

            } else {
                $car = new CarModel();
                $info = $car->getCarById($car_id,'car_id, company, vin');
                $info = decode_array($info);
                $info['belong_company'] = $info['company'];
                unset($info['company']);

            }

            //查询省市区
            $region_model = new RegionModel();
            //查询获取省份
            $where = [
                'parent_id'     => 1,
                'region_level'  => 1
            ];
            $config['province'] = $region_model->getRegion($where,'region_id,region_name');

            $plate_color = plate_color();
            $energy_type = fuel_type();
            $fix_state = fix_state();
            $check_state = check_state();

            $this->assign($config);
            $this->assign('info',$info);
            $this->assign('plate_color',$plate_color);
            $this->assign('energy_type',$energy_type);
            $this->assign('inspection_status',$fix_state);
            $this->assign('annual_review_status',$check_state);

            return $this->fetch();
    }

    public function supplement_submits() {
        $post_supplement_data = input('post.');     //post获取参数
        $arr = explode('&', $post_supplement_data['data']);//转成数组
        $supplement_data = array();
        foreach ($arr as $k => $v) {
            $arr = explode('=', $v);
            $supplement_data[$arr[0]] = $arr[1];
        }

        $car_id = $supplement_data['car_id'];

        if($supplement_data['valid_end'] <= $supplement_data['valid_start'])  {
            return json(['status'=>1,'msg'=>'运输证有效时间不能小于失效时间！']);
        }

        foreach ($supplement_data as $key => $value) {
            if($key != 'car_id' && $key != 'city_id' && $key != 'plate_color' && $key != 'inspection_status' && $key != 'annual_review_status' && $key != 'service_type') {
                $supplement_data[$key] = Security::encrypt($value);
            }
        }

        //城市编码code
        $city = Db::table('xm_region')->field('region_code')->where('region_id', $supplement_data['city_id'])->find();

        $supplement_data['city_code'] = $city['region_code'];

        $info = Db::table('xm_car_info_supplement')->where('car_id',$car_id)->find();
        if($info) {
            Db::table('xm_car_info_supplement')->where('car_id', $info['car_id'])->update($supplement_data);
        } else {
            Db::table('xm_car_info_supplement')->insert($supplement_data);
        }

        return json(['status'=>1,'msg'=>'操作成功！']);
    }

    public function ajax_supplement() {
        $post_supplement_data = input('post.');     //post获取参数
        $arr = explode('&', $post_supplement_data['data']);//转成数组
        $supplement_data = array();
        foreach ($arr as $k => $v) {
            $arr = explode('=', $v);
            $supplement_data[$arr[0]] = $arr[1];
        }
        $car_id = $supplement_data['car_id'];

        $car_info = Db::table('xm_car_info')->where('car_id', $car_id)->find();
        $data_address = Db::table('xm_region')->field('region_code')->where('region_id',$supplement_data['city_id'])->find();

        //组装数据
        $post_data = [];
        $post_data['CompanyId'] = "3401HMKJ8P2R";
        $post_data['Address'] = $data_address['region_code'];
        $post_data['VehicleNo'] = Security::decrypt($car_info['car_plate']);
        $post_data['PlateColor'] = $supplement_data['plate_color'];  //车辆颜色
        $post_data['Seats'] = $car_info['seats'];
        $post_data['Brand'] = Security::decrypt($supplement_data['car_label']);
        $post_data['Model'] = Security::decrypt($car_info['car_model']);
        $post_data['VehicleType'] = Security::decrypt($supplement_data['car_type']);  //例 小型汽车
        $post_data['OwnerName'] = Security::decrypt($car_info['owner']);
        $post_data['VehicleColor'] = Security::decrypt($car_info['color']);
        $post_data['EngineId'] = Security::decrypt($supplement_data['engine_id']);
        $post_data['VIN'] = Security::decrypt($supplement_data['vin']);
        $post_data['CertifyDateA'] = date('Ymd', $car_info['register_at']);
        $post_data['FuelType'] = Security::decrypt($supplement_data['energy_type']);;  //车辆燃料类型
        $post_data['EngineDisplace'] = Security::decrypt($supplement_data['engine_capacity']);
        $post_data['TransAgency'] = Security::decrypt($supplement_data['issuing_agency']);
        $post_data['TransArea'] = Security::decrypt($supplement_data['manage_area']);
        $post_data['TransDateStart'] = date('Ymd',strtotime(Security::decrypt($supplement_data['valid_start'])));
        $post_data['TransDateStop'] = date('Ymd',strtotime(Security::decrypt($supplement_data['valid_end'])));
        $post_data['CertifyDateB'] = date('Ymd',strtotime(Security::decrypt($supplement_data['first_register_date'])));
        $post_data['FixState'] = $supplement_data['inspection_status'];
        $post_data['CheckState'] = $supplement_data['annual_review_status'];
        $post_data['FeePrintId'] = Security::decrypt($supplement_data['fee_print_id']);
        $post_data['GPSBrand'] = Security::decrypt($supplement_data['gps_brand']);
        $post_data['GPSModel'] = Security::decrypt($supplement_data['gps_model']);
        $post_data['GPSInstallDate'] = date('Ymd',strtotime(Security::decrypt($supplement_data['install_date'])));
        $post_data['RegisterDate'] = date('Ymd',strtotime(Security::decrypt($supplement_data['register_date'])));
        $post_data['CommercialType'] = $supplement_data['service_type'];
        $post_data['FareType'] = "xmcx01";
        $post_data['State'] = 0;
        $post_data['Flag'] = 1;
        $post_data['UpdateTime'] = date('YmdHis',time());

        //提交url 到java接口
        $post_url = Env::get('javaTraffic'.ENV.'_host')."/47";
        $res = Tools::request_post($post_url, json_encode($post_data));

        if($res == 200) {
            return json(['code'=>1,'msg'=>'success']);
        } else {
            return json(['code'=>0,'msg'=>'error']);
        }
    }
}
